<template>
  <el-scrollbar :wrap-class="{ wrapClass: true }">
    <div class="app-container">
      <div class="filter-container" size="small">
        <el-input
          v-model="listQuery.name"
          size="small"
          :placeholder="$t('common.username')"
          style="width: 150px"
          class="filter-item"
          clearable
        />
        <!--        <el-input-->
        <!--          v-model="listQuery.mobile"-->
        <!--          size="small"-->
        <!--          placeholder="手机号码"-->
        <!--          style="width: 150px;"-->
        <!--          class="filter-item"-->
        <!--          clearable-->
        <!--        />-->
        <el-select
          v-model="listQuery.ruleId"
          size="small"
          :placeholder="$t('user.ruleGroup')"
          filterable
          clearable
          style="width: 130px"
        >
          <el-option
            v-for="item in ruleTemplates"
            v-if="item.state == 1"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="listQuery.state"
          size="small"
          :placeholder="$t('common.status')"
          filterable
          clearable
          class="filter-item"
          style="width: 120px"
        >
          <el-option key="1" :label="$t('common.enable')" value="1" />
          <el-option key="2" :label="$t('common.disabled')" value="2" />
        </el-select>
        <el-select
          v-if="isSysAdmin"
          v-model="listQuery.oemId"
          size="small"
          :placeholder="$t('user.trademark')"
          filterable
          clearable
          class="filter-item"
          style="width: 150px"
        >
          <el-option
            v-for="item in oems"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>

        <date-selector v-model="listQuery.validity" style="width: 250px" />
        <el-button
          class="filter-item"
          size="small"
          icon="el-icon-search"
          type="primary"
          plain
          @click="search"
        >
          {{ $t('table.search') }}
        </el-button>
        <el-alert
          class="tipTitle"
          :title="tipUser()"
          type="warning"
          :closable="false"
        />
        <el-button
          v-if="showAddButton"
          class="filter-item"
          size="small"
          icon="el-icon-plus"
          type="primary"
          @click="add"
        >
          {{ $t('table.add') }}
        </el-button>
        <el-button
          size="small"
          class="filter-item right"
          icon="el-icon-refresh"
          type="primary"
          plain
          @click="refresh"
        >
          {{ $t('common.refresh') }}
        </el-button>
      </div>

      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        :height="
          listQuery.total > 0 ? 'calc(100vh - 205px)' : 'calc(100vh - 170px)'
        "
        :header-cell-style="{ background: '#F2F6FC' }"
        element-loading-text="Loading"
        fit
        border
        size="medium"
      >
        <el-table-column
          align="center"
          :label="$t('common.id')"
          width="50"
          type="index"
        />
        <el-table-column :label="$t('common.username')" min-width="200px">
          <template slot-scope="scope">
            <strong>{{ userData[scope.row.id]['userName'] }}</strong>
          </template>
        </el-table-column>
        <el-table-column :label="$t('user.truename')" min-width="200px">
          <template slot-scope="scope">
            <strong>{{ userData[scope.row.id]['trueName'] }}</strong>
          </template>
        </el-table-column>
        <el-table-column :label="$t('user.ruleGroup')" min-width="110px">
          <template slot-scope="scope">
            {{ makeRuleName(scope.row.ruleId) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.status')" width="80" align="center">
          <template slot-scope="scope">
            <strong v-if="scope.row.state === 1" style="color: #67c23a">{{
              $t('common.enable')
            }}</strong>
            <strong v-else style="color: #f56c6c">{{
              $t('common.disabled')
            }}</strong>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.validity')"
          width="100px"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.validity }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="isSysAdmin"
          :label="$t('user.brandName')"
          min-width="150px"
        >
          <template slot-scope="scope">
            {{ makeOemName(scope.row.oemId) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.createTime')"
          width="160px"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.createdAt }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          prop
          :label="$t('common.actions')"
          width="250"
        >
          <template slot-scope="scope">
            <el-button-group>
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('user.ruleManagement')"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-view"
                  @click="editAuth(userData[scope.row.id]['id'])"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('route.CompanyConfig')"
                placement="top"
              >
                <el-button
                  size="mini"
                  icon="el-icon-setting"
                  @click="editConfig(scope.row.id)"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('common.edit')"
                placement="top"
              >
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="edit(userData[scope.row.id]['id'])"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('user.resetPassword')"
                placement="top"
              >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-refresh-left"
                  @click="resetPassword(userData[scope.row.id]['id'])"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('customer.operationLog')"
                placement="top"
              >
                <el-button
                  type="info"
                  size="mini"
                  icon="el-icon-tickets"
                  @click="viewLog(userData[scope.row.id]['id'])"
                />
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <pagination
        v-show="listQuery.total > 0"
        :total="listQuery.total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="fetchData"
      />

      <add-page :show.sync="showAddState" @closeAction="closeAction" />
      <edit-page :id="id" :show.sync="showState" @closeAction="closeAction" />
      <user-log-page :id="id" :show.sync="showLogState" />
      <config-page
        :id="id"
        :show.sync="configState"
        @closeAction="closeAction"
      />
      <authority-page
        :userId="id"
        :show.sync="authorityState"
        @closeAction="closeAuth"
      />
    </div>
  </el-scrollbar>
</template>

<style scoped>
.app-container {
  min-width: 900px;
  padding-bottom: 10px;
}
</style>

<script>
import Pagination from '@/components/Pagination'
import DateSelector from '@/components/Public/dateSelector.vue'
import AddPage from '@/views/userManage/company/add'
import EditPage from '@/views/userManage/company/edit'
import UserLogPage from '@/views/userManage/userLog'
import ConfigPage from '@/views/userManage/company/config'
import { getAction, postAction } from '@/api/common'
import AuthorityPage from '@/views/userManage/ruleTemplate/authority'
import { UserModule } from '@/store/modules/user'

export default {
  name: 'index',
  components: {
    Pagination,
    AddPage,
    EditPage,
    ConfigPage,
    UserLogPage,
    DateSelector,
    AuthorityPage,
  },
  data() {
    return {
      id: '',
      listLoading: true,
      list: [],
      userData: [],
      // 列表搜索条件
      listQuery: {
        page: 1,
        total: 0,
        limit: 20,
        name: '',
        mobile: '',
        ruleId: '',
        state: '',
        oemId: '',
        validity: [],
      },
      companyConfig: {
        isOpenUser: 1,
        openUserNum: 0,
      },
      rule: [],
      ruleTemplates: [],
      isSysAdmin: false,
      oems: [],
      showState: false,
      showAddState: false,
      showLogState: false,
      configState: false,
      authorityState: false,
      showAddButton: true,
    }
  },
  created() {
    this.getSearchList()
    this.fetchData()
  },
  methods: {
    async getSearchList() {
      this.listLoading = true
      const { data } = await getAction({}, 'UserCompany/GetCompanySearchList')
      this.rule = data.rule
      this.ruleTemplates = data.ruleTemplates
      this.oems = data.oems
      this.isSysAdmin = data.isSysAdmin
      this.companyConfig = data.companyConfig
      console.log(this.oems)
    },
    async fetchData() {
      this.listLoading = true

      const listQuery = JSON.parse(JSON.stringify(this.listQuery))
      if (listQuery.state === '') {
        listQuery.state = 0
      }
      if (listQuery.ruleId === '') {
        listQuery.ruleId = -1
      }
      if (listQuery.oemId === '') {
        listQuery.oemId = -1
      }
      if (listQuery.validity != null && listQuery.validity.length != 0) {
        listQuery.validityStart = listQuery.validity[0]
        listQuery.validityEnd = listQuery.validity[1] + ' 23:59:59'
      }

      const { data } = await getAction(listQuery, 'UserCompany/GetCompanyList')
      this.list = data.companyData.items
      this.listQuery.total = data.companyData.total
      this.userData = data.userList
      this.listLoading = false
    },
    makeRuleName(ruleId) {
      if (typeof this.ruleTemplates[ruleId] !== 'undefined') {
        return this.ruleTemplates[ruleId]['name']
      } else {
        return this.$t('common.empty')
      }
    },
    makeOemName(oemId) {
      if (typeof this.oems[oemId] !== 'undefined') {
        return this.oems[oemId]['name']
      } else {
        return this.$t('user.trademarkExpired')
      }
    },
    add() {
      this.showAddState = true
    },
    edit(id) {
      this.id = id
      this.showState = true
    },
    viewLog(id) {
      this.showLogState = true
      this.id = id
    },
    editConfig(id) {
      this.configState = true
      this.id = id
    },
    editAuth(id) {
      this.id = id
      this.authorityState = true
    },
    async resetPassword(id) {
      this.$confirm(
        this.$t('user.confirmResetPasswordTo', ['123456']),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('permission.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
        }
      )
        .then(async () => {
          await postAction({ id: id }, 'UserCompany/resetPassword')
          this.$notify({
            title: this.$t('common.success'),
            message: this.$t('user.resetSuccessfully'),
            type: 'success',
            duration: 2000,
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('user.resetCanceled'),
          })
        })
    },
    search() {
      this.listQuery.page = 1
      this.fetchData()
    },
    refresh() {
      this.fetchData()
    },
    closeAuth() {
      this.authorityState = false
    },
    closeAction() {
      this.showState = false
      this.showAddState = false
      this.configState = false
      this.getSearchList()
      this.fetchData()
    },
    tipUser() {
      let msg = ''
      // eslint-disable-next-line eqeqeq
      if (this.companyConfig.isOpenUser == 2) {
        msg = Number(this.companyConfig.openUserNum)
        // eslint-disable-next-line eqeqeq
        if (msg == 0) {
          msg = 0 + '人'
          this.showAddButton = false
        }
      } else {
        msg = this.$t('common.noLimit')
      }
      return this.$t('user.remainOpenUser') + msg
    },
  },
}
</script>
